<template>
	<div class="sys-user-container">
		<el-row :gutter="8" style="width: 100%;height: 100%;">
			<el-col :span="4" :xs="24">
				<OrgTree ref="orgTreeRef" @node-click="nodeClick" />
			</el-col>

			<el-col :span="20" :xs="24" style="display:flex;flex-direction:column;">
				<el-card shadow="hover" class="tabSearch_Bar" :body-style="{ paddingBottom: '0' }">
					<TableSearch :search="tb.tableData.search" @search="onSearch" />
				</el-card>
				<el-card class="full-table" shadow="hover" style="margin-top: 8px">
					<Table ref="tableRef" v-bind="tb.tableData" :getData="getData" :exportChangeData="exportChangeData" @sortHeader="onSortHeader" @selectionChange="tableSelection">
						<template #command>
							<el-button type="primary" icon="ele-Plus" @click="openAddUser" v-auth="'sysUser:add'"> 新增 </el-button>
							<el-button icon="ele-Paperclip" v-auth="'sysUser:add'"> 导入 </el-button>
							<el-button icon="ele-Download" v-auth="'sysUser:add'"> 导出 </el-button>
							<el-dropdown size="small" split-button class="spaceDropDown">
								开具证明
								<template #dropdown>
								<el-dropdown-menu>
									<el-dropdown-item :icon="Stamp">在职证明</el-dropdown-item>
									<el-dropdown-item :icon="Flag">离职证明</el-dropdown-item> 
								</el-dropdown-menu>
								</template>
							</el-dropdown>
							<el-button icon="ele-Present" v-auth="'sysUser:add'"> 生日名单 </el-button> 
							<el-button type="danger" icon="ele-Delete" v-auth="'sysUser:delete'"> 批量删除 </el-button>
							<el-dropdown size="small" split-button class="spaceDropDown">
								其它
								<template #dropdown>
								<el-dropdown-menu>
									<el-dropdown-item :icon="Bell">员工提醒</el-dropdown-item> 
									<el-dropdown-item :icon="Postcard">员工发卡</el-dropdown-item> 
								</el-dropdown-menu>
								</template>
							</el-dropdown>
						</template>
						<template #sex="scope">
							<el-tag type="success" v-if="scope.row.sex === 1"> 男 </el-tag>
							<el-tag type="danger" v-else> 女 </el-tag>
						</template>
						<template #orgName="scope">
							{{scope.row.sysOrg.name}}
						</template> 
						<template #joinDate="scope">
							{{ formatDate(new Date(scope.row.joinDate), 'YYYY-mm-dd') }}
						</template>
						<template #age="scope">
							{{ frmatYear(new Date(scope.row.birthday)) }}
						</template>
						<template #status="scope">
							<el-tag type="success" v-if="scope.row.status === 1"> 在职 </el-tag>
							<el-tag type="danger" v-else> 离职 </el-tag>
						</template>
						<template #action="scope">
							<el-button icon="ele-Edit" size="small" text type="primary" @click="openEditEmployee(scope.row)" v-auth="'sysUser:update'"> 编辑 </el-button>
							<el-dropdown>
								<el-button icon="ele-MoreFilled" size="small" text type="primary" style="padding-left: 12px" />
								<template #dropdown>
									<el-dropdown-menu> 
										<el-dropdown-item icon="ele-Delete" @click="delUser(scope.row)" divided :disabled="!auth('sysUser:delete')"> 删除 </el-dropdown-item>
									</el-dropdown-menu>
								</template>
							</el-dropdown>
						</template>
					</Table>
				</el-card>
			</el-col>
		</el-row>

		<EditEmployee ref="editUserRef" :title="state.editUserTitle" :orgData="state.orgTreeData" @handleQuery="handleQuery" />
	</div>
</template>

<script lang="ts" setup name="sysUser">
import {Stamp,Flag,Postcard,Bell} from '@element-plus/icons-vue'
import { onMounted, reactive, ref,defineAsyncComponent, nextTick } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { formatDate,frmatYear } from '/@/utils/formatTime';
import { auth } from '/@/utils/authFunction';
import OrgTree from '/@/views/org/manager/component/orgTree.vue';
import EditEmployee from '/@/views/employee/manage/component/editEmployee.vue';

import { getAPI } from '/@/utils/axios-utils';
import { EmployeeApi, SysOrgApi } from '/@/api-services/api';
import { SysUser, SysOrg } from '/@/api-services/models'; 
import { fa } from 'element-plus/es/locale';

// 引入组件
const Table = defineAsyncComponent(() => import('/@/components/table/index.vue'));
const TableSearch = defineAsyncComponent(() => import('/@/components/table/search.vue'));
const tableRef = ref<RefType>();
const orgTreeRef = ref<InstanceType<typeof OrgTree>>();
const editUserRef = ref<InstanceType<typeof EditEmployee>>();

const state = reactive({
	loading: false,
	selectlist: [] as EmptyObjectType[],
	userData: [] as Array<SysUser>,
	orgTreeData: [] as Array<SysOrg>,
	editUserTitle: '',
});


const tb = reactive<TableDemoState>({
	tableData: {
		// 表头内容（必传，注意格式）
		columns: [
			{ type: 'index', width:50, label: '序号',fixed:'left',align: 'left', isCheck: true },
			{ prop: 'jobNum', width:90, label: '工号',fixed:'left',align: 'left', sortable: 'custom', isCheck: true },
			{ prop: 'realName', width: 90, label: '姓名',fixed:'left', align: 'left',  sortable: 'custom', isCheck: true },		
			{ prop: 'orgName', width: 100, label: '部门',fixed:'left', align: 'left', isCheck: true,'show-overflow-tooltip':true, hideCheck: true},		
			{ prop: 'joinDate', width: 90, label: '入职日期', align: 'left',  sortable: 'custom', isCheck: true },		
			{ prop: 'sex', width: 60, label: '性别', align: 'left', isCheck: true },		
			{ prop: 'age', width: 60, label: '年龄', align: 'left', isCheck: true },		
			{ prop: 'status', width: 60, label: '状态', align: 'left',isCheck: true },		
			{ prop: 'posLevel', width: 60, label: '职级', align: 'left', isCheck: true },		
			{ prop: 'posTitle', width: 90, label: '职称', align: 'left',  isCheck: true },		
			{ prop: 'nation', width: 90, label: '民族', align: 'left', isCheck: true },		
			{ prop: 'remark', label: '备注', align: 'left', isCheck: true },		
			{ prop: 'action', width: 110, label: '操作', type: 'action', align: 'left', isCheck: true, fixed: 'right', hideCheck: true },
		],
		// 配置项（必传）
		config: {
			isStripe: false, // 是否显示表格斑马纹
			isBorder: true, // 是否显示表格边框
			isSerialNo: false, // 是否显示表格序号
			isSelection: true, // 是否勾选表格多选 
			showSelection: auth('sysUser:delete'), //是否显示表格多选
			pageSize: 10, // 每页条数
			hideExport: false, //是否隐藏导出按钮 
			hidePrint:false,//是否隐藏打印按钮
			exportFileName: '员工资料', //导出报表的文件名，不填写取应用名称
		},
		// 搜索表单，动态生成（传空数组时，将不显示搜索，type有3种类型：input,date,select）
		search: [
			{ label: '工号', prop: 'jobNum', placeholder: '搜索工号', required: false, type: 'input' },
			{ label: '姓名', prop: 'realName', placeholder: '搜索姓名', required: false, type: 'input' },
			{ label: '手机号码', prop: 'phone', placeholder: '搜索手机号码', required: false, type: 'input' },
		],
		param: {
			orgId: -1,
			jobNum: undefined,
			realName: undefined,
			phone: undefined,
		},
		defaultSort: {
			prop: 'orderNo',
			order: 'ascending',
		},
		customPrintFun:function(_param:any,_data:any){
			console.log("===================================AAAAA");
		}
	},
});
 
const getData = (param: any) => {
	return getAPI(EmployeeApi)
		.apiEmployeePagePost(param)
		.then((res) => {
			return res.data;
	});
};

//表格多选事件
const tableSelection = (data: EmptyObjectType[]) => {
	// console.log('表格多选事件', data)
	state.selectlist = data;
};
// 拖动显示列排序回调
const onSortHeader = (data: object[]) => {
	tb.tableData.columns = data;
};
// 搜索点击时表单回调
const onSearch = (data: EmptyObjectType) => {
	tb.tableData.param = Object.assign({}, tb.tableData.param, { ...data });
	nextTick(() => {
		tableRef.value.pageReset();
	});
};

const exportChangeData = (data: Array<EmptyObjectType>) => {
	data.forEach((item) => {
		item.sysFlag = item.sysFlag == 1 ? '是' : '否';
	});
	return data;
};
// 查询机构数据
const loadOrgData = async () => {
	state.loading = true;
	var res = await getAPI(SysOrgApi).apiSysOrgListGet(0);
	console.log(res);
	state.orgTreeData = res.data.result ?? [];
	state.loading = false;
};

// 查询操作
const handleQuery = async () => {
	state.loading = true; 
	nextTick(() => {
		tableRef.value.pageReset();
	});
	state.loading = false;
};

// 打开新增页面
const openAddUser = () => {
	state.editUserTitle = '添加账号';
	editUserRef.value?.openDialog({});
};

// 打开编辑页面
const openEditEmployee = (row: any) => {
	state.editUserTitle = '编辑账号';
	editUserRef.value?.openDialog(row);
};

// 删除
const delUser = (row: any) => {
	ElMessageBox.confirm(`确定删除员工记录：【${row.realName}】?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			await getAPI(EmployeeApi).apiEmployeeDeletePost({ id: row.id });
			handleQuery();
			ElMessage.success('删除成功');
		})
		.catch(() => {});
};

// 树组件点击
const nodeClick = async (node: any) => {
	tb.tableData.param.orgId = node.id;
	tb.tableData.param.jobNum = undefined;
	tb.tableData.param.realName = undefined;
	tb.tableData.param.phone = undefined;
	handleQuery();
};

onMounted(async () => {
	loadOrgData();
});
</script>
<style>
.tabSearch_Bar .mb20{
	margin-bottom: 10px !important;
}
.spaceDropDown.el-dropdown{
  margin-left: 10px;
  margin-right: 10px;
}
</style>